package text;// ShoppingCart.java - 购物车
import java.util.HashMap;
import java.util.Map;

public class ShoppingCart {
    private Map<Fruit, Integer> items; // 水果 -> 斤数
    private boolean hasPromotion; // 是否有满减促销
    private int promotionThreshold; // 满减门槛
    private int promotionAmount; // 满减金额

    public ShoppingCart() {
        this.items = new HashMap<>();
        this.hasPromotion = false;
        this.promotionThreshold = 0;
        this.promotionAmount = 0;
    }

    // 设置满减促销
    public void setPromotion(int threshold, int amount) {
        this.hasPromotion = true;
        this.promotionThreshold = threshold;
        this.promotionAmount = amount;
    }

    // 添加水果
    public void addFruit(Fruit fruit, int weight) {
        if (weight < 0) {
            throw new IllegalArgumentException("水果斤数必须大于等于0");
        }
        items.put(fruit, items.getOrDefault(fruit, 0) + weight);
    }

    // 计算总价
    public double calculateTotalPrice() {
        double total = 0.0;
        
        // 计算所有水果的总价
        for (Map.Entry<Fruit, Integer> entry : items.entrySet()) {
            Fruit fruit = entry.getKey();
            int weight = entry.getValue();
            total += fruit.calculatePrice(weight);
        }
        
        // 应用满减促销
        if (hasPromotion && total >= promotionThreshold) {
            total -= promotionAmount;
        }
        
        return Math.max(total, 0); // 确保总价不为负数
    }

    // 显示购物车内容
    public void displayCart() {
        System.out.println("购物车内容:");
        for (Map.Entry<Fruit, Integer> entry : items.entrySet()) {
            Fruit fruit = entry.getKey();
            int weight = entry.getValue();
            double itemTotal = fruit.calculatePrice(weight);
            System.out.printf("  %s: %d斤 * %.1f元", fruit.getName(), weight, fruit.getPrice());
            if (fruit.getDiscount() < 1.0) {
                System.out.printf(" (%.0f折)", fruit.getDiscount() * 100);
            }
            System.out.printf(" = %.1f元\n", itemTotal);
        }
    }
}